package util;

import java.io.File;
import java.io.IOException;

import indexer.ReverseIndex;
import algorithm.text.wordsegment.WordSegmentor;

public class CommonFactory {
	private static final WordSegmentor WORD_SEGMENTOR_INSTANCE;
	private static final ReverseIndex REVERSE_INDEXER_INSTANCE;
	
	static {
		WORD_SEGMENTOR_INSTANCE = new WordSegmentor(Constants.DIC_FOLDER,
				Constants.SINGLE_LETTER_WORD_FILENAME);
		REVERSE_INDEXER_INSTANCE = new ReverseIndex();
		try {
			loadIndexData(REVERSE_INDEXER_INSTANCE);
		} catch (IOException e) {
			System.err.println("Error loading index file, aborted.");
			e.printStackTrace();
		}
	}
	
	/**
	 * 读入Index的数据
	 * @throws IOException 
	 */
	private static void loadIndexData(ReverseIndex ri) throws IOException {
		File dataDir = new File(Constants.INDEX_FOLDER);
		if (!dataDir.exists()) {
			System.out.print("Index[" + Constants.INDEX_FOLDER + 
					"] does NOT exist, building...");
			ri.indexDirectory(Constants.ORIGINAL_FILE_FOLDER, true);
			System.out.println("OK!");
			System.out.print("storing to " + Constants.INDEX_FOLDER + " for future use");
			ri.storeIndex(Constants.INDEX_FOLDER);
			System.out.println("OK!");
		} else {
			if (!dataDir.isDirectory()) {
				System.err.println("Error: index dir is not a directory!");
			}
			System.out.print("Loading " + Constants.INDEX_FOLDER);
			ri.loadIndex(Constants.INDEX_FOLDER);
			System.out.println("OK!");
		}
	}
	
	public static WordSegmentor getWordSegmentor() {
		return WORD_SEGMENTOR_INSTANCE;
	}
	
	public static ReverseIndex getReverseIndex() {
		return REVERSE_INDEXER_INSTANCE;
	}
}
